﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQ.Send
{
    class Program
    {
        /// <summary>
        /// 连接配置
        /// </summary>
        private static readonly ConnectionFactory connectingFactory = new ConnectionFactory()
        {
            HostName = "localhost",
            UserName = "guest",
            Password = "guest",
            Port = 5672,
            Uri = new Uri("amqp://guest:guest@localhost:5672/")
    };
        /// <summary>
        /// 路由名称
        /// </summary>
        const string ExchangeName = "ExchangeName";
        /// <summary>
        /// 队列名称
        /// </summary>
        const string QueueName = "QueueName";


        static void Main(string[] args)
        {
            Console.InputEncoding = Encoding.Unicode;
            Console.OutputEncoding = Encoding.Unicode;
            DirectExchangeSendMsg();

            Console.WriteLine("按任意键退出程序！");
            Console.ReadLine();
        }

        /// <summary>
        /// 单点精确路由模式
        /// </summary>
        private static void DirectExchangeSendMsg()
        {
            using (var conn = connectingFactory.CreateConnection())
            {
                using (IModel channel = conn.CreateModel())
                {
                    channel.ExchangeDeclare(ExchangeName, "direct", durable: true, autoDelete: false, arguments: null);
                    channel.QueueDeclare(QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
                    channel.QueueBind(QueueName, ExchangeName, routingKey: QueueName);

                    var props = channel.CreateBasicProperties();
                    props.Persistent = true;
                    Console.WriteLine("请输入需要发送的消息：");
                    string vadata = Console.ReadLine();
                    while (vadata != "exit")
                    {
                        var msgBody = Encoding.UTF8.GetBytes(vadata);
                        channel.BasicPublish(exchange: ExchangeName, routingKey: QueueName, basicProperties: props, body: msgBody);
                        Console.WriteLine(string.Format("发送时间：{0}，发送完毕，输入exit退出消息发送", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                        vadata = Console.ReadLine();
                    }
                }
            }
        }
    }
}
